package com.sita.bluetactivity.NewBlueTooth;

import android.app.ProgressDialog;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattServer;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;

import com.sita.bluetactivity.Base.BaseApplication;
import com.sita.bluetactivity.Base.BaseValue;
import com.sita.bluetactivity.Base.SpUtils;
import com.sita.bluetactivity.Base.ToastUtils;
import com.sita.bluetactivity.Event.CommunicationEvent;
import com.sita.bluetactivity.Event.RoundtoFindEvent;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import de.greenrobot.event.EventBus;
import retrofit.http.Header;

/**
 * Created by Jason on 2016/9/19.
 *      01020304050607080901
 *  public static String HEART_RATE_MEASUREMENT = "00002a37-0000-1000-8000-00805f9b34fb";
 */
public class BtService extends Service {
    private int deviceIndex =0;
    private CommunicationEvent communicationEvent = new CommunicationEvent();
    private  BluetoothGattCharacteristic communicationChar;  //通信用的
    private  BluetoothGatt bluetoothGatt;
    private  StopFindEvent event;   //当蓝牙连接成功之后给Main发送指令去寻车
    private List<BluetoothDevice> bluetoothDevices = new ArrayList<>();
    private String pass;//密码
    private BindVehicleMsg bindVehicleMsg;
    private BluetoothDevice bluetoothDevice;
    private MyHandler handler = new MyHandler();
    class MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    Log.e("1000000000000001","请求密码指令");
                    btBinder.CommunicationWrite("18180D0D010000000000000D0A");
                    break;
                case 2:
                    Log.e("1000000000000001","请求密码指令");
                    //寻车辆状态

                    Log.e("sssss","18180D04"+SpUtils.getString("ConnectionPass",null, BaseApplication.getContext())+"0100000D0A");
                    btBinder.CommunicationWrite("18180D04"+SpUtils.getString("ConnectionPass",null, BaseApplication.getContext())+"0100000D0A");
                    break;
            }

        }
    }
    private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {

        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            if (status==BluetoothGatt.GATT_SUCCESS){
                //首先判断这个status   如果等于 BluetoothGatt.GATT_SUCCESS（value=0）代表这个回调是正常的，
                //如果不等于 0，那边就代表没有成功，也不需要进行其他操作了，
                // 连接成功和断开连接都会走到这里
                bluetoothGatt = gatt;
                switch (newState){
                    case BluetoothGatt.STATE_CONNECTED: //连接成功
                        gatt.discoverServices();//寻找设备中的服务
                        BaseValue.BtIsConnection = true;
                        break;
                    case BluetoothGatt.STATE_DISCONNECTED: //连接失败
                        Log.e("1000000000000001","连接失败"+ bluetoothDevices.get(deviceIndex).getName());
                        BaseValue.BtIsConnection = false;
                        break;
                    case BluetoothGatt.STATE_CONNECTING:
                        Log.e("1000000000000001","正在连接");
                        break;
                    case BluetoothGatt.STATE_DISCONNECTING:
                        Log.e("1000000000000001","断开连接中");
                        BaseValue.BtIsConnection = false;
                        break;
                }

            }

        }
    /**********************************查找服务蓝牙特征值**********************************/
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
            if (status==BluetoothGatt.GATT_SUCCESS){
                //找到服务 ==获取蓝牙中所有的服务和特征值UUID
                Log.e("1000000000000001","Service成功");
                List<BluetoothGattService> data = gatt.getServices();
                for (BluetoothGattService service:data){
                    List<BluetoothGattCharacteristic> characdata = service.getCharacteristics();
                    for (BluetoothGattCharacteristic characteristic:characdata){


                        if (characteristic.getUuid().toString().equals("0000ffe1-0000-1000-8000-00805f9b34fb")){
                            //获取到连接时的特征值
                            Log.e("1000000000000001  :  ",characteristic.getUuid().toString());
                            communicationChar = characteristic;
                            //开启这个特征值的通知权限
                            bluetoothGatt.setCharacteristicNotification(characteristic, true);
                            //发送特征值
                            EventBus.getDefault().post(communicationEvent);
                            //发送密码请求
                            if (BaseValue.isFirstConnection){
                                handler.sendEmptyMessage(1);
                            }else {
                                handler.sendEmptyMessage(2);
                            }

                        }
                    }
                }
            }
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
          //读取蓝牙设备发过来的数据

        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicWrite(gatt, characteristic, status);
             //获取写入的结果，
            if (status==BluetoothGatt.GATT_SUCCESS){
                Log.e("1000000000000001","写入正常");
            }else if (status==BluetoothGatt.GATT_FAILURE){
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
          //  thread.stop();

            //知道是哪一个特征值发的命令，获取写入指令的通知指令
            Log.e("1000000000000001","@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"+communicationChar);
            //判断返回密码
            getData(communicationChar);

        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        bindVehicleMsg = new BindVehicleMsg();
    }

    private BtBinder btBinder = new BtBinder();
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return btBinder;
    }
    public class BtBinder extends Binder{
       public String dn;

       //连接蓝牙
        public void connection(BluetoothDevice device)   {
            if (device.getName()!=null){
                device.connectGatt(BtService.this,false,mGattCallback);//第二个参数，是否设置自动重连
                dn=device.getName();
                bluetoothDevice = device;//现在的设备
            }
            Log.e("1000000000000001",dn +"正在连接中");
        }

        /**
         * 连接通信时验证的byte
         * 写入
         */
        public void CommunicationWrite(String Msg){
            if (bluetoothGatt!=null&&communicationChar!=null){
                communicationChar.setValue(hexStringToBytes(Msg));
                bluetoothGatt.writeCharacteristic(communicationChar);
                Log.e("1000000000000001","，这是后就等待回调了");
            }
        }

        public void disConnected(){
            if (bluetoothGatt!=null){
                bluetoothGatt.disconnect();
                bluetoothGatt.setCharacteristicNotification(communicationChar,false);
                bluetoothGatt.close();
                BaseValue.BtIsConnection = false;
            }

        }


       //搜索之后找到所有的蓝牙设备
       public void getDeviceList(List<BluetoothDevice> devices ) {
           bluetoothDevices = devices;
           deviceIndex =0;


       }
    }
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }
    private static byte charToByte(char c) {
        int index = "0123456789ABCDEF".indexOf(c);
        if (index == -1) {
            index = "0123456789abcdef".indexOf(c);
        }
        return (byte) index;
    }

//判断蓝牙密码

    private void getData(BluetoothGattCharacteristic communicationChar){

        Log.e("1000000000000001","返回的密码值:  "+byteTX( communicationChar.getValue()).substring(8,16));
        pass = byteTX(communicationChar.getValue()).substring(8,16);
             //18180A0D代码密码的回调
            if (byteTX( communicationChar.getValue()).substring(0,8).equals("18180A0D")){
                if (pass!=null&&pass.equals("41414141")){
                    BaseValue.BtIsConnection = false;
                    //密码错误，断开连接
                    btBinder.disConnected();
                    setData(++deviceIndex);
                }
                else {
                    //
                    BaseValue.BtIsConnection = true;
                    //此时连接到的蓝牙设备，将正确的密码保存下载
                    event = new StopFindEvent();
                    event.setPass(pass);
                    SpUtils.putString("ConnectionPass",pass, BaseApplication.getContext());
                    SpUtils.putString("DeviceID",bluetoothDevices.get(deviceIndex).getName(),BaseApplication.getContext());
                    EventBus.getDefault().post(event);
                    //发送广播
                    Intent intent = new Intent();
                    bindVehicleMsg.controller_pass = pass;
                    bindVehicleMsg.controller_address = bluetoothDevice.getAddress();
                    bindVehicleMsg.controller_id = bluetoothDevice.getName();
                    bindVehicleMsg.user_id =Long.valueOf(SpUtils.getString("AccountId",null,BaseApplication.getContext()));

                    intent.setAction("com.sita.bluetactivity.ISOK");

                    intent.putExtra("VehicleMsg",bindVehicleMsg);
                    sendBroadcast(intent);


                }
            }
       }

    private void setData(int deviceIndex){
        Log.e("1000000000000001","当前的设备"+    deviceIndex+ " xx   "  + bluetoothDevices.size()+" vvvv");

        if (deviceIndex>=bluetoothDevices.size()){
            Log.e("1000000000000001","设备 全部扫描完毕");
            return;
        }
       btBinder.connection(bluetoothDevices.get(deviceIndex));
        //进行连接的时候需要继续发送密码指令
    }

    public static String byteTX(byte[] x){
        String ret = "";
        for (byte abyte:x){
            String hex = Integer.toHexString(abyte&0xFF);
            if (hex.length()==1){
                hex = '0'+hex;
            }
            ret+=hex.toUpperCase(Locale.CANADA);
        }
        return ret;
    }
}
